package cn.virens.server.netty_tcp;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import cn.virens.server.netty_tcp.packet.TcpWritePacket;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;

public class TCPServerChannel implements Serializable {
	private static final long serialVersionUID = -947516044734319749L;

	private final Map<String, Object> attrs = new ConcurrentHashMap<>();

	private final AtomicInteger heatTimes = new AtomicInteger(0);
	private final AtomicInteger heatIdle = new AtomicInteger(0);

	private final ChannelHandlerContext context;
	private final String mac;

	public TCPServerChannel(ChannelHandlerContext context, String mac) {
		this.context = context;
		this.mac = mac;
	}

	public String getMac() {
		return mac;
	}

	@SuppressWarnings("unchecked")
	public <T> T getAttr(String key) {
		return (T) attrs.get(key);
	}

	@SuppressWarnings("unchecked")
	public <T> T setAttr(String key, T value) {
		return (T) attrs.put(key, value);
	}

	public AtomicInteger heatIdle() {
		return heatIdle;
	}

	public AtomicInteger heatTimes() {
		return heatTimes;
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(context);
	}

	@Override
	public boolean equals(Object obj) {
		return Objects.hashCode(obj) == hashCode();
	}

	@Override
	public String toString() {
		return context + "[" + mac + "]";
	}

	public ChannelFuture write(TcpWritePacket msg) {
		return context.writeAndFlush(msg);
	}
}
